<template>
    <div>
        <div v-if="connected">
            <input v-model="message" placeholder="输入消息" />
            <button @click="sendMessage">发送消息</button>
        </div>
        <div v-else>
            <p>连接中...</p>
        </div>
        <div>
            <h2>接收到的消息：</h2>
            <ul>
                <li v-for="(msg, index) in receivedMessages" :key="index">{{ msg }}</li>
            </ul>
        </div>
        <lay-button type="normal" @click="link">链接</lay-button>
    </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'


const connected = ref(false)
const message = ref('')
const receivedMessages = ref([])
// 本体
let socket
const link = () => {
    socket = new WebSocket('ws://localhost:8080');
    socket.onopen = () => {
        connected.value = true;
    };
    socket.onmessage = async (event) => {
        if (event.data instanceof Blob) {
            const reader = new FileReader()
            reader.readAsText(event.data, "UTF-8");
            reader.onload = (e) => {
                console.log(reader.result, 'reader.result')
                if (isJson(reader.result)) {
                    let result = JSON.parse(reader.result);
                    console.log(result, 'result')
                    receivedMessages.value.push(result);
                } else {
                    receivedMessages.value.push(reader.result);
                }

            }
        }

    };

}
onUnmounted(() => {
    socket.onclose = () => {
        connected.value = false;
    };
})
function sendMessage() {
    if (connected.value && message.value.trim() !== '') {
        socket.send(message.value);
        message.value = '';
    }
}

function isJson(str) {
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
}


</script>

<style lang="scss" scoped></style>